package com.adam.example.util;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import jakarta.json.stream.JsonGenerator;

import java.io.StringWriter;

public class JsonUtil {

    public static String searchRequestToJson(SearchRequest searchRequest, ElasticsearchClient elasticsearchClient) {
        return searchRequestToJson(searchRequest, elasticsearchClient._jsonpMapper());
    }

    public static String searchRequestToJson(SearchRequest searchRequest) {
        return searchRequestToJson(searchRequest, new JacksonJsonpMapper());
    }

    public static String searchRequestToJson(SearchRequest searchRequest, JsonpMapper jsonpMapper) {
        StringWriter stringWriter = new StringWriter();
        JsonGenerator generator = jsonpMapper.jsonProvider().createGenerator(stringWriter);
        searchRequest.serialize(generator, jsonpMapper);
        generator.close();
        return stringWriter.toString();
    }

}
